package com.chixing.service.impl;

import com.chixing.pojo.Myorder;
import com.chixing.service.MyorderService;
import com.chixing.util.ServerResponse;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by BSY on2021/10/22 20:57
 */
@Service
public class MsgListener {

    @Autowired
    private MyorderService myorderService;

    /**
     * 默认情况下,如果没有配置手动ACK, 那么Spring Data AMQP 会在消息消费完毕后自动帮我们去ACK
     * 存在问题：如果报错了,消息不会丢失,但是会无限循环消费,一直报错,如果开启了错误日志很容易就吧磁盘空间耗完
     * 解决方案：手动ACK,或者try-catch 然后在 catch 里面将错误的消息转移到其它的系列中去
     * spring.rabbitmq.listener.simple.acknowledge-mode = manual
     * list 监听的内容
     */

//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(value = "ORDER_QUEUE", autoDelete = "false"),
//                    exchange = @Exchange(value = "ORDER_EXCHANGE", delayed = "true", type = "x-delayed-message"),
//                    key = "ORDER.KEY"
//            )
//    )
    @RabbitListener(queues = "ORDER_QUEUE")
    public void getMyOrderMessage(Myorder myorder, Channel channel, Message message) throws InterruptedException, IOException {
        System.out.println("消息接收到了");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 模拟执行任务+
        System.out.println("这是插件延迟队列消费：" + myorder.getMyorderStatus() + "：" + sdf.format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        try {
            Myorder myOrder = myorderService.getMyOrder(myorder.getMyorderNo());
            if (myOrder.getMyorderStatus() == 0){
                myorderService.updateByMyorderId(myorder.getMyorderId(),3);
                System.out.println("订单失效订单状态更改的状态为：" + myorder.getMyorderNo());
            }else{
                System.out.println("该订单已处理：" + myOrder.getMyorderNo());
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.out.println(("============消费失败,尝试消息补发再次消费!=============="));
            System.out.println(e.getMessage());
            /**
             * basicRecover方法是进行补发操作，
             * 其中的参数如果为true是把消息退回到queue但是有可能被其它的consumer(集群)接收到，
             * 设置为false是只补发给当前的consumer
             */
            channel.basicRecover(false);
        }
    }
}
